﻿using LittleBee.Cells;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LittleBee.AppServ
{
    static class PointerUpdatedServer
    {
        static public void Start()
        {
            Task.Run(() =>
            {
                CellService.Instance.PointerUpdated += OnPointerdUpdated;
                Program.WaitForAppServInitialized();

                Task.Run(() =>
                {
                    while (true)
                    {
                        JArray jaPointer = new JArray();
                        while (_quePointerUpdated.TryDequeue(out PointerUpdatedEventArgs? pointer) == true)
                        {
                            if (pointer != null)
                                jaPointer.Add(pointer.ToJsonObject());
                        }

                        if (jaPointer.Count > 0)
                            JsonRpcInterface.AppServJsonRpcObject.PushPointerValueHandler(jaPointer);
                    }
                });
            });
        }

        private static void OnPointerdUpdated(PointerUpdatedEventArgs e)
        {
            _quePointerUpdated.Enqueue(e);
        }

        private static ConcurrentQueue<PointerUpdatedEventArgs> _quePointerUpdated = new ConcurrentQueue<PointerUpdatedEventArgs>();

		//private static Dictionary<Int64, ConcurrentQueue<PointerUpdatedEventArgs>> _dctUpdatedPointers = new Dictionary<Int64, ConcurrentQueue<PointerUpdatedEventArgs>>();

		static public void RegisterMonitoringCell(Int64 appid)
        {
            CellService.Instance.SetCellMonitoringState(appid, true);
        }
        static public void UnregisterMonitoringCell(Int64 appid)
        {
            CellService.Instance.SetCellMonitoringState(appid, false);
        }

        static public void RegisterMonitoringCell(Int64 appid, string pid)
        {
            CellService.Instance.SetCellMonitoringState(appid, true);
        }
        static public void UnregisterMonitoringCell(Int64 appid, string pid)
        {
            CellService.Instance.SetCellMonitoringState(appid, false);
        }
    }
}
